<?php 
namespace app\admin\controller;
class Field extends Common {

	public function index(){
		$model_id = \mylib\Input::get('model_id');
		$this -> assign('model_id', $model_id);
		
		$fields = \Ebcms::db() -> select('field', '*', [
			'model_id' => $model_id,
			'ORDER' => [
				'weight' => 'ASC',
				'id' => 'ASC',
			]
		]);
		$groups = [];
		foreach ($fields as $key => $value) {
			if (!isset($groups[$value['group']])) {
				$groups[$value['group']] = [];
			}
			$groups[$value['group']][] = $value;
		}
		$this -> assign('groups', $groups);
		return $this -> html($this -> fetch());
	}

	public function add(){
		if (\Ebcms::isPost()) {
			$model_id = \mylib\Input::post('model_id');
			\Ebcms::db() -> insert('field', [
				'model_id'=>\mylib\Input::post('model_id'),
				'group'=>\mylib\Input::post('group'),
				'title'=>\mylib\Input::post('title'),
				'field'=>\mylib\Input::post('field'),
				'type'=>\mylib\Input::post('type'),
				'config'=>\mylib\Input::post('config'),
				'tips'=>\mylib\Input::post('tips'),
				'style'=>\mylib\Input::post('style'),
				'weight'=>\mylib\Input::post('weight'),
				'admin_show'=>\mylib\Input::post('admin_show'),
			]);
			return $this -> success('操作成功！', \mylib\Route::buildUrl('/admin/field/index') . '?model_id=' . $model_id);
		}else{
			$model_id = \mylib\Input::get('model_id');
			$this -> assign('model_id', $model_id);
			return $this -> html($this -> fetch());
		}
	}

	public function edit(){
		if (\Ebcms::isPost()) {
			$model_id = \mylib\Input::post('model_id');
			\Ebcms::db() -> update('field', [
				'group'=>\mylib\Input::post('group'),
				'title'=>\mylib\Input::post('title'),
				'field'=>\mylib\Input::post('field'),
				'type'=>\mylib\Input::post('type'),
				'config'=>\mylib\Input::post('config'),
				'tips'=>\mylib\Input::post('tips'),
				'style'=>\mylib\Input::post('style'),
				'weight'=>\mylib\Input::post('weight'),
				'admin_show'=>\mylib\Input::post('admin_show'),
			], [
				'id'=>\mylib\Input::post('id')
			]);
			return $this -> success('操作成功！', \mylib\Route::buildUrl('/admin/field/index').'?model_id='.$model_id);
		}else{
			$field = \Ebcms::db() -> get('field', '*', ['id'=>\mylib\Input::get('id')]);
			$this -> assign('field', $field);
			return $this -> html($this -> fetch());
		}
	}

	public function del(){
		if (\Ebcms::isAjax()) {
			\Ebcms::db() -> delete('field', [
				'id'=>\mylib\Input::post('id'),
			]);
			return $this -> success('操作成功！');
		}
	}
}